<template>
  <div class="log-container">
    <el-card class="log-card">
      <template #header>
        <div class="card-header">
          <span class="card-title">操作日志管理</span>
          <div class="card-actions">
            <el-button type="warning" @click="cleanLogs" :loading="cleaning">
              清理旧日志
            </el-button>
            <el-button type="success" @click="exportLogs" :loading="exporting">
              导出日志
            </el-button>
          </div>
        </div>
      </template>

      <!-- 统计信息 -->
      <div class="statistics-section">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-card shadow="hover" class="stat-card">
              <div class="stat-item">
                <div class="stat-number">{{ statistics.today_count || 0 }}</div>
                <div class="stat-label">今日日志</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="stat-card">
              <div class="stat-item">
                <div class="stat-number">{{ statistics.week_count || 0 }}</div>
                <div class="stat-label">本周日志</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="stat-card">
              <div class="stat-item">
                <div class="stat-number">{{ statistics.month_count || 0 }}</div>
                <div class="stat-label">本月日志</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="stat-card">
              <div class="stat-item">
                <div class="stat-number">{{ total }}</div>
                <div class="stat-label">总日志数</div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 筛选条件 -->
      <div class="filter-section">
        <el-form :model="filterForm" inline>
          <el-form-item label="关键词">
            <el-input
              v-model="filterForm.keyword"
              placeholder="搜索描述、URL、用户名"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="模块">
            <el-select v-model="filterForm.module" placeholder="选择模块" clearable style="width: 150px">
              <el-option
                v-for="module in modules"
                :key="module"
                :label="module"
                :value="module"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="filterForm.status" placeholder="选择状态" clearable style="width: 120px">
              <el-option label="成功" value="success" />
              <el-option label="错误" value="error" />
              <el-option label="警告" value="warning" />
            </el-select>
          </el-form-item>
          <el-form-item label="时间范围">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="loadLogs">查询</el-button>
            <el-button @click="resetFilter">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 日志列表 -->
      <div class="log-table">
        <el-table
          :data="logList"
          v-loading="loading"
          stripe
          style="width: 100%"
          @row-click="showLogDetail"
        >
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="username" label="用户" width="120" />
          <el-table-column prop="action" label="操作" width="150" />
          <el-table-column prop="module" label="模块" width="120" />
          <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
          <el-table-column prop="request_method" label="方法" width="80" />
          <el-table-column prop="response_code" label="状态码" width="100">
            <template #default="{ row }">
              <el-tag :type="row.response_code === 200 ? 'success' : 'danger'">
                {{ row.response_code }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="execution_time" label="耗时(秒)" width="100">
            <template #default="{ row }">
              <span :class="getExecutionTimeClass(row.execution_time)">
                {{ row.execution_time }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="80">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)">
                {{ getStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="ip_address" label="IP地址" width="120" />
          <el-table-column prop="created_at" label="时间" width="160">
            <template #default="{ row }">
              {{ formatDateTime(row.created_at) }}
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>

    <!-- 日志详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      title="日志详情"
      width="800px"
      :before-close="closeDetail"
    >
      <div v-if="selectedLog" class="log-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="ID">{{ selectedLog.id }}</el-descriptions-item>
          <el-descriptions-item label="用户">{{ selectedLog.username }}</el-descriptions-item>
          <el-descriptions-item label="操作">{{ selectedLog.action }}</el-descriptions-item>
          <el-descriptions-item label="模块">{{ selectedLog.module }}</el-descriptions-item>
          <el-descriptions-item label="描述" :span="2">{{ selectedLog.description }}</el-descriptions-item>
          <el-descriptions-item label="请求方法">{{ selectedLog.request_method }}</el-descriptions-item>
          <el-descriptions-item label="状态码">{{ selectedLog.response_code }}</el-descriptions-item>
          <el-descriptions-item label="请求URL" :span="2">{{ selectedLog.request_url }}</el-descriptions-item>
          <el-descriptions-item label="请求参数" :span="2">
            <pre v-if="selectedLog.request_params" class="params-pre">{{ formatParams(selectedLog.request_params) }}</pre>
            <span v-else>无</span>
          </el-descriptions-item>
          <el-descriptions-item label="响应消息" :span="2">{{ selectedLog.response_message || '无' }}</el-descriptions-item>
          <el-descriptions-item label="IP地址">{{ selectedLog.ip_address }}</el-descriptions-item>
          <el-descriptions-item label="执行时间">{{ selectedLog.execution_time }}秒</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(selectedLog.status)">
              {{ getStatusText(selectedLog.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDateTime(selectedLog.created_at) }}</el-descriptions-item>
          <el-descriptions-item label="用户代理" :span="2">{{ selectedLog.user_agent || '无' }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>

    <!-- 清理日志对话框 -->
    <el-dialog v-model="cleanVisible" title="清理旧日志" width="400px">
      <el-form :model="cleanForm" label-width="100px">
        <el-form-item label="保留天数">
          <el-input-number
            v-model="cleanForm.days"
            :min="7"
            :max="365"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item>
          <span class="clean-tip">将删除指定天数之前的日志记录</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cleanVisible = false">取消</el-button>
          <el-button type="warning" @click="confirmClean" :loading="cleaning">
            确认清理
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useApi } from '@/composables/useApi'
import * as dayjs from 'dayjs'

const api = useApi()

// 数据
const loading = ref(false)
const cleaning = ref(false)
const exporting = ref(false)
const logList = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(20)
const statistics = ref({})
const modules = ref([])
const detailVisible = ref(false)
const cleanVisible = ref(false)
const selectedLog = ref(null)
const dateRange = ref([])

// 筛选表单
const filterForm = reactive({
  keyword: '',
  module: '',
  status: '',
  start_date: '',
  end_date: ''
})

// 清理表单
const cleanForm = reactive({
  days: 30
})

// 监听日期范围变化
const updateDateRange = () => {
  if (dateRange.value && dateRange.value.length === 2) {
    filterForm.start_date = dateRange.value[0]
    filterForm.end_date = dateRange.value[1]
  } else {
    filterForm.start_date = ''
    filterForm.end_date = ''
  }
}

// 加载日志列表
const loadLogs = async () => {
  try {
    loading.value = true
    updateDateRange()
    
    const params = {
      ...filterForm,
      page: currentPage.value,
      limit: pageSize.value
    }
    
    const response = await api.get('/logs', { params })
    
    if (response.code === 200) {
      logList.value = response.data.list
      total.value = response.data.total
    } else {
      ElMessage.error(response.message || '获取日志列表失败')
    }
  } catch (error) {
    console.error('获取日志列表失败:', error)
    ElMessage.error('获取日志列表失败')
  } finally {
    loading.value = false
  }
}

// 加载统计信息
const loadStatistics = async () => {
  try {
    const response = await api.get('/logs/statistics')
    if (response.code === 200) {
      statistics.value = response.data
    }
  } catch (error) {
    console.error('获取统计信息失败:', error)
  }
}

// 加载模块列表
const loadModules = async () => {
  try {
    const response = await api.get('/logs/modules')
    if (response.code === 200) {
      modules.value = response.data
    }
  } catch (error) {
    console.error('获取模块列表失败:', error)
  }
}

// 重置筛选条件
const resetFilter = () => {
  Object.assign(filterForm, {
    keyword: '',
    module: '',
    status: '',
    start_date: '',
    end_date: ''
  })
  dateRange.value = []
  currentPage.value = 1
  loadLogs()
}

// 分页处理
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  loadLogs()
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
  loadLogs()
}

// 显示日志详情
const showLogDetail = (row: any) => {
  selectedLog.value = row
  detailVisible.value = true
}

// 关闭详情对话框
const closeDetail = () => {
  detailVisible.value = false
  selectedLog.value = null
}

// 清理日志
const cleanLogs = () => {
  cleanForm.days = 30
  cleanVisible.value = true
}

// 确认清理
const confirmClean = async () => {
  try {
    cleaning.value = true
    const response = await api.post('/logs/clean', cleanForm)
    
    if (response.code === 200) {
      ElMessage.success(`成功清理${response.data.deleted_count}条旧日志`)
      cleanVisible.value = false
      loadLogs()
      loadStatistics()
    } else {
      ElMessage.error(response.message || '清理失败')
    }
  } catch (error) {
    console.error('清理日志失败:', error)
    ElMessage.error('清理日志失败')
  } finally {
    cleaning.value = false
  }
}

// 导出日志
const exportLogs = async () => {
  try {
    exporting.value = true
    updateDateRange()
    
    const params = { ...filterForm }
    const response = await api.get('/logs/export', { params })
    
    if (response.code === 200) {
      ElMessage.success('日志导出成功')
      // 这里可以添加下载文件的逻辑
    } else {
      ElMessage.error(response.message || '导出失败')
    }
  } catch (error) {
    console.error('导出日志失败:', error)
    ElMessage.error('导出日志失败')
  } finally {
    exporting.value = false
  }
}

// 工具函数
const formatDateTime = (dateStr: string) => {
  return dayjs(dateStr).format('YYYY-MM-DD HH:mm:ss')
}

const formatParams = (params: string) => {
  try {
    return JSON.stringify(JSON.parse(params), null, 2)
  } catch {
    return params
  }
}

const getStatusType = (status: string) => {
  const types = {
    success: 'success',
    error: 'danger',
    warning: 'warning'
  }
  return types[status] || 'info'
}

const getStatusText = (status: string) => {
  const texts = {
    success: '成功',
    error: '错误',
    warning: '警告'
  }
  return texts[status] || status
}

const getExecutionTimeClass = (time: number) => {
  if (time > 1) return 'text-danger'
  if (time > 0.5) return 'text-warning'
  return 'text-success'
}

// 页面加载
onMounted(() => {
  loadLogs()
  loadStatistics()
  loadModules()
})
</script>

<style scoped>
.log-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.log-card {
  max-width: 1400px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.card-actions {
  display: flex;
  gap: 10px;
}

.statistics-section {
  margin-bottom: 20px;
}

.stat-card {
  text-align: center;
}

.stat-item {
  padding: 10px;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.filter-section {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #fafafa;
  border-radius: 4px;
}

.log-table {
  margin-top: 20px;
}

.pagination-wrapper {
  margin-top: 20px;
  text-align: right;
}

.log-detail {
  max-height: 500px;
  overflow-y: auto;
}

.params-pre {
  background-color: #f5f5f5;
  padding: 10px;
  border-radius: 4px;
  font-size: 12px;
  white-space: pre-wrap;
  word-break: break-all;
}

.clean-tip {
  color: #909399;
  font-size: 12px;
}

.text-success {
  color: #67c23a;
}

.text-warning {
  color: #e6a23c;
}

.text-danger {
  color: #f56c6c;
}
</style> 